package fun.codedesign.eclipse.jdt;

import org.eclipse.jdt.core.dom.*;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * <a href="https://blog.51cto.com/u_16213336/6989656">...</a>
 */
public class WriteNewMethod {

    @Test
    public void step1() {
        // 创建一个AST的访问者
        ASTVisitor visitor = new ASTVisitor() {
            @Override
            public boolean visit(TypeDeclaration node) {
                AST ast = node.getAST();
                // 修改AST，添加新的方法
                MethodDeclaration method = ast.newMethodDeclaration();
                method.setName(ast.newSimpleName("hello"));
                node.bodyDeclarations().add(method);

                Block block = ast.newBlock();

                SingleVariableDeclaration singleVariableDeclaration = ast.newSingleVariableDeclaration();
//                singleVariableDeclaration.setName(ast.newSimpleName("Map<String,String> map"));

//                VariableDeclarationFragment variableDeclarationFragment = ast.newVariableDeclarationFragment()

                Assignment assignment =  ast.newAssignment();

//                VariableDeclarationExpression variableDeclarationExpression = ast.newVariableDeclarationExpression()

                assignment.setLeftHandSide(ast.newSimpleName("a"));
                assignment.setOperator(Assignment.Operator.ASSIGN);
                assignment.setRightHandSide(ast.newArrayCreation());

                block.statements().add(ast.newExpressionStatement(assignment));


                method.setBody(block);
                return super.visit(node);
            }
        };


        // 创建ASTParser实例
        ASTParser parser = ASTParser.newParser(AST.JLS11);

        // 设置ASTParser的输入和选项
        parser.setKind(ASTParser.K_COMPILATION_UNIT);
        parser.setSource(CodeExample.EXAMPLE1.toCharArray());
        parser.setResolveBindings(true);

        // 获取AST，并将其转换为可执行的Java源代码
        CompilationUnit compiledUnit = (CompilationUnit) parser.createAST(null);
        compiledUnit.accept(visitor);
        String newCode = compiledUnit.toString();
        System.out.println(newCode);

        // 创建一个新的Java文件
        File file = new File("GeneratedClass.java");
        // 写入生成的Java源代码到文件中
        try (FileWriter writer = new FileWriter(file)) {
            writer.write(newCode);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
